/**
 * Created by Su on 2014/11/18.
 */


/**
 * 替换选中的文本
 * @param {jquery-object} $o
 * @param {String} str
 * @returns {void}
 * @example replaceSelection($(this).parent().find('textarea'), 'abc');
 * @since 1.0 2014-7-3 by sutroon
 */
function replaceSelection($o, str) {
    var _o = $o.get(0);
    if (!_o)
        return;
    if (checkBrowser() == 'IE') {
        _o.focus();
        var sel = document.selection.createRange();
        sel.text = str;
        sel.select();
    } else if (_o.selectionStart || _o.selectionStart == '0') {
        var startPos = _o.selectionStart;
        var endPos = _o.selectionEnd;
        var restoreTop = _o.scrollTop;
        _o.value = _o.value.substring(0, startPos) + str + _o.value.substring(endPos, _o.value.length);
        if (restoreTop > 0) {
            _o.scrollTop = restoreTop;
        }
        _o.focus();
        _o.selectionStart = startPos + str.length;
        _o.selectionEnd = startPos + str.length;
    }
}

/**
 * 检测浏览器类型
 * @returns {String}
 * @since 1.0 2014-7-3 by sutroon
 */
function checkBrowser() {
    var browserName = navigator.userAgent.toLowerCase();
    if (/msie/i.test(browserName) && !/opera/.test(browserName)) {
        return "IE";
    } else if (/firefox/i.test(browserName)) {
        return "Firefox";
    } else if (/chrome/i.test(browserName) && /webkit/i.test(browserName) && /mozilla/i.test(browserName)) {
        return "Chrome";
    } else if (/opera/i.test(browserName)) {
        return "Opera";
    } else if (/webkit/i.test(browserName) && !(/chrome/i.test(browserName) && /webkit/i.test(browserName) && /mozilla/i.test(browserName))) {
        return "Safari";
    } else {
        return 'unKnow';
    }
}